package com.youdoneed.common.service;

import com.youdoneed.common.util.StringUuidUtil;
import it.sauronsoftware.jave.*;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2018/1/23 0023.
 */
@Service
public class ConvertorServiceImpl implements ConvertorService {

    @Override
    public File m4aConvertor(File file) {
        String uuid = StringUuidUtil.getUUID();
        File target = new File(FileServiceStatic.fileAddress.concat(uuid)
                .concat(FileServiceStatic.fileFormatmp3));
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(new Integer(64000));
        audio.setChannels(new Integer(1));
        audio.setSamplingRate(new Integer(22050));
        VideoAttributes video = new VideoAttributes();
        video.setCodec("mp3");
        video.setBitRate(new Integer(160000));
        video.setFrameRate(new Integer(15));
        video.setSize(new VideoSize(400, 300));
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        attrs.setVideoAttributes(video);
        Encoder encoder = new Encoder();
        try {
            encoder.encode(file, target, attrs);
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return target;
    }

    @Override
    public File multipartToFile(MultipartFile multfile) throws IOException{
        String uuid = StringUuidUtil.getUUID();
        File file = new File(FileServiceStatic.fileAddress.concat(uuid)
                .concat(FileServiceStatic.fileFormatm4a));
        FileUtils.copyInputStreamToFile(multfile.getInputStream(), file);
        return file;
    }

    @Override
    public MultipartFile multfile(File file) throws IOException {
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile
                ("file", file.getName(), "text/plain", IOUtils.toByteArray(input));

        if (input !=null){
            input.close();
        }
        return multipartFile;
    }


}
